/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI.TOOL;

import POJO.CauHinh;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

/**
 *
 * @author Khôi
 */
public class BackupDatabase extends javax.swing.JFrame {

	/**
	 * Creates new form BackupDatabase
	 */
	public BackupDatabase() {
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the
	 * form. WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
       // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
       private void initComponents() {

              jButton1 = new javax.swing.JButton();
              txDatabase = new javax.swing.JTextField();
              jLabel3 = new javax.swing.JLabel();
              txMasster = new javax.swing.JTextField();
              jLabel8 = new javax.swing.JLabel();
              txUser = new javax.swing.JTextField();
              txPort = new javax.swing.JTextField();
              jButton2 = new javax.swing.JButton();
              txPass = new javax.swing.JTextField();
              jLabel5 = new javax.swing.JLabel();
              jLabel6 = new javax.swing.JLabel();
              jLabel2 = new javax.swing.JLabel();
              jLabel1 = new javax.swing.JLabel();
              txPath = new javax.swing.JTextField();
              txServer = new javax.swing.JTextField();
              jLabel7 = new javax.swing.JLabel();

              setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
              setTitle("Sao lưu CSDL");

              jButton1.setText("Backup");
              jButton1.setToolTipText("Tạo database tên QL");
              jButton1.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(java.awt.event.ActionEvent evt) {
                            jButton1ActionPerformed(evt);
                     }
              });

              txDatabase.setText("QLBH");

              jLabel3.setText("User sử dụng:");

              txMasster.setText("master");

              jLabel8.setText("Port:");

              txUser.setText("nhom1");

              txPort.setText("1433");

              jButton2.setText("Hủy");
              jButton2.setToolTipText("Xóa database tên QL");
              jButton2.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(java.awt.event.ActionEvent evt) {
                            jButton2ActionPerformed(evt);
                     }
              });

              txPass.setText("123");

              jLabel5.setText("Pass của user trên:");

              jLabel6.setText("Đường dẫn:");

              jLabel2.setText("CSDL sẽ backup:");

              jLabel1.setText("Database master:");

              txPath.setText("C:\\QLBH.bak");

              txServer.setText("localhost");

              jLabel7.setText("Server name:");

              javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
              getContentPane().setLayout(layout);
              layout.setHorizontalGroup(
                     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addContainerGap(223, Short.MAX_VALUE)
                            .addComponent(jButton1)
                            .addGap(18, 18, 18)
                            .addComponent(jButton2)
                            .addGap(115, 115, 115))
                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                   .addContainerGap()
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                          .addComponent(jLabel7)
                                          .addComponent(jLabel1)
                                          .addComponent(jLabel2)
                                          .addComponent(jLabel3)
                                          .addComponent(jLabel5)
                                          .addComponent(jLabel6)
                                          .addComponent(jLabel8))
                                   .addGap(18, 18, 18)
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                          .addComponent(txPort, javax.swing.GroupLayout.Alignment.LEADING)
                                          .addComponent(txMasster, javax.swing.GroupLayout.Alignment.LEADING)
                                          .addComponent(txDatabase, javax.swing.GroupLayout.Alignment.LEADING)
                                          .addComponent(txUser, javax.swing.GroupLayout.Alignment.LEADING)
                                          .addComponent(txPass, javax.swing.GroupLayout.Alignment.LEADING)
                                          .addComponent(txPath, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 322, Short.MAX_VALUE)
                                          .addComponent(txServer))
                                   .addContainerGap(31, Short.MAX_VALUE)))
              );
              layout.setVerticalGroup(
                     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addContainerGap(230, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                   .addComponent(jButton1)
                                   .addComponent(jButton2))
                            .addGap(25, 25, 25))
                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                   .addGap(47, 47, 47)
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                          .addComponent(txServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                          .addComponent(jLabel7))
                                   .addGap(5, 5, 5)
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                          .addComponent(txPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                          .addComponent(jLabel8))
                                   .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                          .addComponent(txMasster, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                          .addComponent(jLabel1))
                                   .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                          .addComponent(txDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                          .addComponent(jLabel2))
                                   .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                          .addComponent(txUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                          .addComponent(jLabel3))
                                   .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                          .addComponent(txPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                          .addComponent(jLabel5))
                                   .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                   .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                          .addComponent(txPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                          .addComponent(jLabel6))
                                   .addContainerGap(56, Short.MAX_VALUE)))
              );

              pack();
       }// </editor-fold>//GEN-END:initComponents

       private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

		this.setEnabled(false);
		if (backup()) {
			JOptionPane.showMessageDialog(this, "Backup thành công. Xem trong thư mục: " + txPath.getText().trim(), "Thông báo thành công ",JOptionPane.INFORMATION_MESSAGE);

		}
				this.setEnabled(true);

       }//GEN-LAST:event_jButton1ActionPerformed
	public boolean backup() {
		String ketNoiMasster = "jdbc:sqlserver://"
			 + txServer.getText().trim()
			 + ":" + txPort.getText().trim()
			 + ";databaseName=" + txMasster.getText().trim()
			 + ";";
		boolean flag = backupDatabase(ketNoiMasster, txUser.getText().trim(), txPass.getText().trim());
		return flag;
	}

	public boolean backupDatabase(String data, String user, String pass) {
		try {

			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			Connection conn = DriverManager.getConnection(data, user, pass);
			System.out.println("connected");
			Statement statement = conn.createStatement();
			boolean flag = false;
			String res = "BACKUP DATABASE " + txDatabase.getText().trim() + " TO DISK = '" + txPath.getText() + "';";//' WITH REPLACE, NOUNLOAD, STATS = 10;";
			try {
				flag = statement.execute(res);

			} catch (SQLException e) {
				JOptionPane.showMessageDialog(this, "Không thể backup CSDL", "Thông báo lỗi", JOptionPane.ERROR_MESSAGE);

				System.out.println("Không thể backup CSDL");
				conn.close();
				this.setVisible(true);

				return false;
			}

			System.out.println(flag + " Backup xong ");
			conn.close();
			System.out.println("Đón kết nối ");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
       private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
		// TODO add your handling code here:
		//   xoa();
		this.dispose();
       }//GEN-LAST:event_jButton2ActionPerformed

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
		 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(BackupDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(BackupDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(BackupDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(BackupDatabase.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new BackupDatabase().setVisible(true);
			}
		});
	}
       // Variables declaration - do not modify//GEN-BEGIN:variables
       private javax.swing.JButton jButton1;
       private javax.swing.JButton jButton2;
       private javax.swing.JLabel jLabel1;
       private javax.swing.JLabel jLabel2;
       private javax.swing.JLabel jLabel3;
       private javax.swing.JLabel jLabel5;
       private javax.swing.JLabel jLabel6;
       private javax.swing.JLabel jLabel7;
       private javax.swing.JLabel jLabel8;
       private javax.swing.JTextField txDatabase;
       private javax.swing.JTextField txMasster;
       private javax.swing.JTextField txPass;
       private javax.swing.JTextField txPath;
       private javax.swing.JTextField txPort;
       private javax.swing.JTextField txServer;
       private javax.swing.JTextField txUser;
       // End of variables declaration//GEN-END:variables
}
